import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  // 首页，页面组件路由
  {
    path: '/',
    name: 'Home',
    component: ()=>import(/*webpackChunkName:"home"*/ '../views/Home/Home'),
  },
  // 我的，页面组件路由
  {
    path:'/my',
    name:'My',
    component:()=>import(/*webpackChunkName:"my"*/ '../views/My/My'),
  },
  // 我的地址管理，页面组件路由
  {
    path:'/myaddress',
    name:'MyAddress',
    component:()=>import(/*webpackChunkName:"myaddress"*/ '../views/MyAddress/MyAddress'),
  },
  // 我的新建地址，页面组件路由
  {
    path:'/newaddress',
    name:'NewAddress',
    component:()=>import(/*webpackChunkName:"newaddress"*/ '../views/NewAddress/NewAddress'),
  },
  // 我的编辑地址，页面组件路由
  {
    path:'/changeaddress/:id',
    name:'ChangeAddress',
    component:()=>import(/*webpackChunkName:"changeaddress"*/ '../views/ChangeAddress/ChangeAddress'),
  },
  // 商家详情，页面组件路由
  {
    path: '/shop/:id',
    name: 'Shop',
    component: ()=>import(/*webpackChunkName:"shop"*/ '../views/Shop/Shop'),
  },
  // 确认订单，页面组件路由
  {
    path: '/confirmation/:id',
    name: 'Confirmation',
    component: ()=>import(/*webpackChunkName:"confirmation"*/ '../views/Confirmation/Confirmation'),
  },
  // 购物车，页面组件路由
  {
    path:'/cartlist',
    name:'CartList',
    component:()=>import(/*webpackChunkName:"cartlist"*/ '../views/CartList/CartList')
  },
  // 订单，页面组件路由
  {
    path: '/order',
    name: 'Order',
    component: ()=>import(/*webpackChunkName:"order"*/ '../views/Order/Order'),
  },
  // 登陆，页面组件路由
  {
    path: '/login',
    name: 'Login',
    component: ()=>import(/*webpackChunkName:"login"*/ '../views/Login/Login'),
    // 在进入页面之前执行的方法
    beforeEnter(to,from,next){
      const {isLogin}=sessionStorage;
      // 判断是否已经登陆
      if (isLogin) {
        // 如果已经登陆就跳转到首页
        next({name:'Home'})
      } else {
        // 如果没有登陆就可以跳转到要跳转的登陆页面
        next()
      }
    }
  },
  // 注册，页面组件路由
  {
    path: '/register',
    name: 'Register',
    component: ()=>import(/*webpackChunkName:"register"*/ '../views/Register/Register'),
    beforeEnter(to,from,next){
      const {isLogin}=sessionStorage;
      // 判断是否已经登陆
      if (isLogin) {
        // 如果已经登陆就跳转到首页
        next({name:'Home'})
      } else {
        // 如果没有登陆就可以跳转到要跳转的注册页面
        next()
      }
    }
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 在每次跳转页面时要执行的方法
router.beforeEach((to,from,next)=>{
  const {isLogin} = sessionStorage;
  // 如果已经登陆，或者要跳转的页面是登陆或者注册页面，就可以跳转到目的页面
  if(isLogin || to.name==='Login' ||to.name==="Register") {
    next();
  } else {
    // 如果没有登陆并且要跳转的页面不是登陆或者注册页面，就跳转到登陆页面
    next({name:'Login'});
  }
})

export default router


